<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                              |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: anguolei@clcw.com.cn                                           |
// +------------------------------------------------------------------------+
//
namespace AuctionCore\Finance;

use AuctionCore\CarResource\CarModel;
use AuctionCore\Other\Address;
use AuctionCore\Other\Coupon;
use AuctionCore\System\AuctionException;
use AuctionCore\ChangeOrder\ChangeOrder;
use AuctionCore\CarDealer\Dealer;
use AuctionCore\AntNest\UserCenter;

/**
 * 收款
 * @author Angl
 */
class Collection
{
    public function __construct()
    {

    }

    /**
     * 新增收款信息
     * 拍单ID,创建时间
     * @param $data
     * @return mixed
     */
    public static function add($data)
    {
        $data['createtime'] = date("Y-m-d H:i:s");
        return M('proceeds_log')->add($data);
    }

    public static function getProceedInfoByOrderID($orderID)
    {
        return M('proceeds_log')->where("order_id=" . $orderID)->find();
    }

    /**
     * 更新收款信息
     * @param $order_id
     * @param $data
     * @return bool
     */
    public static function update_by_order_id($order_id, $data)
    {
        if ($order_id < 1) return false;
        return M('proceeds_log')->where(['order_id' => $order_id])->save($data); //"order_id=" . $order_id
    }

    /**
     * 收款列表
     * @param $page
     * @param $limit
     * @param array $params
     * @return array
     */
    public function get_list($page, $limit, $params = array())
    {
        $page = intval($page) > 0 ? intval($page) : 1;
        $limit = intval($limit) > 0 ? intval($limit) : 10;
        $map = [];
        //1、线下全款 2、有首付贷款
        $map['pl.pay_mode'] = [['eq', 1], ['eq', 2], 'OR'];
        $map['o.dealer_pay_status'] = intval($params['status']);
        //待收,核实收款 必须是过户前
        if ($params['status'] < 3) {
            $map['o.status'] = 8;
        }
        //车辆所在地
        if (!empty($params['location_area'])) {
            $map['c.location_area'] = ['in', $params['location_area']];
        }
        //车辆编号
        if (!empty($params['car_no'])) {
            $map['c.car_no'] = ['LIKE', '%' . trim($params['car_no']) . '%'];
        }
        //车商联系人/联系人电话/拍卖单号
        if (!empty($params['keywords'])) {
            $keywords = trim($params['keywords']);
            if(is_numeric($params['keywords'])){
                $uc = new UserCenter();
                $info1 = $uc->info_bymobile($params['keywords'],2,1);
                $where['du.uid'] = array('eq',$info1['account_id']);
            }else{
                $where['o.order_no'] = ['LIKE', '%' . $keywords . '%'];
                $where['d.contact_person'] = ['LIKE', '%' . $keywords . '%'];
                $where['_logic'] = 'OR';
            }
            $map['_complex'] = $where;
        }
        //付款类型
        if ($params['pay_mode']) {
            $map['o.dealer_pay_mode'] = ['eq', $params['pay_mode']];
        }
        $cols = "o.order_id,o.order_no,o.status,o.dealer_pay_status,o.dealer_pay_mode,o.business_verify_status,o.is_lock,
                c.car_no,c.location_area,c.car_id,c.brand_id,c.series_id,c.model_id,
                d.contact_person,du.uid,pl.pay_type,pl.pay_time,pl.settlement_time";
        $prefix = C("DB_PREFIX");
        $total = M('proceeds_log')->alias("pl")
            ->join($prefix . "order as o ON o.order_id=pl.order_id")
            ->join($prefix . "cars as c ON c.car_id=o.car_id")
            ->join($prefix . "dealer_auctioned as da ON da.order_id=o.order_id AND da.status=0")
            ->join($prefix . "car_dealer as d ON d.dealer_id=da.dealer_id")
            ->join($prefix . "dealer_user as du ON d.dealer_id=du.dealer_id")
//            ->join(" LEFT JOIN " . $prefix . "loan_log as ll ON ll.order_id=pl.order_id")
            ->where($map)->count();
        $list = M('proceeds_log')->alias("pl")->field($cols)
            ->join($prefix . "order as o ON o.order_id=pl.order_id")
            ->join($prefix . "cars as c ON c.car_id=o.car_id")
            ->join($prefix . "dealer_auctioned as da ON da.order_id=o.order_id AND da.status=0")
            ->join($prefix . "car_dealer as d ON d.dealer_id=da.dealer_id")
            ->join($prefix . "dealer_user as du ON d.dealer_id=du.dealer_id")
//            ->join(" LEFT JOIN " . $prefix . "loan_log as ll ON ll.order_id=pl.order_id")
            ->where($map)->page($page)->limit($limit)->order("pl.createtime desc")->select();
        if(!empty($list)){
            $dealer = new Dealer();
            $list= $dealer->get_contact_mobile_byAntNest($list);
        }
//       echo M()->getLastSql();
        if (!empty($list)) {
            $cm = new CarModel();
            $addr = new Address();
            foreach ($list as $key => $vl) {
                //车型
                $brand = $cm->get_model_by_id($vl['brand_id'], 'brand');
                $series = $cm->get_model_by_id($vl['series_id'], 'series');
                $model = $cm->get_model_by_id($vl['model_id']);
                $list[$key]['car_model'] = $brand['name'] . $series['name'] . $model['name'];
                //所在地
                if ($vl['location_area']) {
                    $location_area = $addr->get_name_by_code($vl['location_area']);
                    $list[$key]['location_area_str'] = $location_area;
                } else {
                    $list[$key]['location_area'] = '无';
                }
                $list[$key]['settlement_time'] = $vl['settlement_time'] > 0 ? $vl['settlement_time'] : '--';
            }
        }
        $data = ['total' => $total, 'list' => $list];
        return $data;
    }

    /**
     * 付款跟踪列表
     * @param $page
     * @param $limit
     * @param array $params
     * @return array
     */
    public function pay_track_list($page, $limit, $params = array())
    {
        $page = intval($page) > 0 ? intval($page) : 1;
        $limit = intval($limit) > 0 ? intval($limit) : 10;
        $map = [];
        //待结算,待收,核实收款 必须是过户前
        if ($params['status'] == 1) { //待结算
            $map['o.dealer_pay_status'] = ['eq', 0];
        } elseif ($params['status'] == 2) {   //待付车款
            $map['o.dealer_pay_status'] = ['eq', 1];
            $map['o.status'] = ['eq', 8];
        } elseif ($params['status'] == 3) { //核实车款
            $map['o.dealer_pay_status'] = ['eq', 2];
            $map['o.business_verify_status'] = ['eq', 1];
        } elseif ($params['status'] == 4) { //收款失败
            $map['o.dealer_pay_status'] = [['eq', 4], ['eq', 5], 'OR'];
            // $map['o.status'] = 8;
        } elseif ($params['status'] == 5) { //收款成功
            $map['o.dealer_pay_status'] = ['eq', 3];
        }
        $map['o.status'] = ['neq',12];
        //车辆所在地
        if (!empty($params['location_area'])) {
            $map['c.location_area'] = ['in', $params['location_area']];
        }
        if (!empty($params['keyword'])) {
            if(is_numeric($params['keyword'])){
                $uc = new UserCenter();
                $info1 = $uc->info_bymobile($params['keyword'],2,1);
                $where['du.uid'] = array('eq',$info1['account_id']);
            }else{
                $keyword = "%{$params['keyword']}%";
                $where['o.order_no'] = array('like', $keyword);
                $where['d.contact_person'] = array('like', $keyword);
                $where['_logic'] = 'or';
            }
            $map['_complex'] = $where;
        }
        //付款类型 -- 全款or贷款
        if ($params['pay_mode']) {
            $map['o.dealer_pay_mode'] = ['eq', $params['pay_mode']];
        }
        //收款状态
        if ($params['pay_status']) {
            switch ($params['pay_status']) {
                case 1:                                                 //全款待收款
                    $map['o.business_verify_status'] = ['eq', 0];
                    $map['o.dealer_pay_mode'] = ['eq', 1];
//                    $map['ll.first_pay_money'] = ['eq', 0];
                    break;
                case 2:                                                 //首付待收款
                    $map['ll.first_pay_money'] = ['gt', 0];
                    break;
                case 3:                                                 //全款待核实
                    $map['o.dealer_pay_mode'] = ['eq', 1];
                    $map['o.dealer_pay_status'] = ['eq', 2];
                    break;
                case 4:                                                 //首付待核实
                    $map['o.dealer_pay_mode'] = ['eq', 2];
                    $map['ll.first_pay_money'] = ['gt', 0];
                    break;
                case 5:                                                 //收款失败
                    $map['o.dealer_pay_status'] = ['eq', 5];
                    break;
                case 6:                                                 //已锁定
                    $map['o.dealer_pay_status'] = ['eq', 4];
                    break;
            }
        }
        //付款类型和收款状态组合查询
        $pay_mode = $params['pay_mode'];
        $pay_status = $params['pay_status'];
        if ($pay_mode == 1) {
            if ($pay_status == 2) {       //全款 + 首付待收
                $map['o.dealer_pay_mode'] = ['eq', 1];
                $map['o.business_verify_status'] = ['eq', 0];
            } elseif ($pay_status == 4) {  //全款 + 首付核实
                $map['o.dealer_pay_mode'] = ['eq', 1];
            }
        } elseif ($pay_mode == 2) {
            if ($pay_status == 1) {      //贷款 + 全款待收
                $map['o.dealer_pay_mode'] = ['eq', 2];
                $map['ll.first_pay_money'] = ['eq', 0];
            } elseif ($pay_status == 3) { //贷款 + 全款核实
                $map['o.dealer_pay_mode'] = ['eq', 2];
                $map['ll.first_pay_money'] = ['eq', 0];
            }
        }
        $cols = "o.order_id,o.order_no,o.status,o.is_lock,o.dealer_pay_status,o.dealer_pay_mode,o.business_verify_status,
                c.location_area,c.car_id,c.brand_id,c.series_id,c.model_id,
                d.contact_person,du.uid,d.dealer_id,r.recheck_time,
                ll.first_pay_money,pl.createtime,pl.pay_time,pl.violatetime,pl.settlement_time";
        $prefix = C("DB_PREFIX");
        $total = M('proceeds_log')->alias("pl")
            ->join($prefix . "order as o ON o.order_id=pl.order_id")
            ->join($prefix . "cars as c ON c.car_id=o.car_id")
            ->join($prefix . "car_dealer as d ON d.dealer_id=o.success_dealer_id")
            ->join($prefix . "dealer_user as du ON d.dealer_id=du.dealer_id")
            ->join('left join ' . $prefix . "recheck as r ON r.car_id =c.car_id")
            ->join('left join ' . $prefix . "loan_log as ll ON ll.order_id =pl.order_id")
            ->where($map)->count();

        $list = M('proceeds_log')->alias("pl")->field($cols)
            ->join($prefix . "order as o ON o.order_id=pl.order_id")
            ->join($prefix . "cars as c ON c.car_id=o.car_id")
            ->join($prefix . "car_dealer as d ON d.dealer_id=o.success_dealer_id")
            ->join($prefix . "dealer_user as du ON d.dealer_id=du.dealer_id")
            ->join('left join ' . $prefix . "recheck as r ON r.car_id =c.car_id")
            ->join('left join ' . $prefix . "loan_log as ll ON ll.order_id =pl.order_id")
            ->where($map)->page($page)->limit($limit)->order("pl.createtime desc")->select();

        if(!empty($list)){
            $dealer = new Dealer();
            $list = $dealer->get_contact_mobile_byAntNest($list);
        }
       // echo M()->getlastsql();
        if (!empty($list)) {
            $cm = new CarModel();
            $addr = new Address();
            foreach ($list as $key => $vl) {
                //车型
                $brand = $cm->get_model_by_id($vl['brand_id'], 'brand');
                $series = $cm->get_model_by_id($vl['series_id'], 'series');
                $model = $cm->get_model_by_id($vl['model_id']);
                $list[$key]['car_model'] = $brand['name'] . $series['name'] . $model['name'];
                //所在地
                if ($vl['location_area']) {
                    $location_area = $addr->get_name_by_code($vl['location_area']);
                    $list[$key]['location_area_str'] = $location_area;
                } else {
                    $list[$key]['location_area'] = '无';
                }
                $list[$key]['createtime'] = empty($vl['createtime']) ? "--" : date('Y年m月d日 H:i', strtotime($vl['createtime']));
                $list[$key]['settlement_time'] = $vl['settlement_time'] > 0 ? date('Y年m月d日 H:i', strtotime($vl['settlement_time'])) : '--';
                $list[$key]['violatetime'] = date('Y年m月d日 H:i', strtotime($vl['violatetime']));
                $list[$key]['pay_time'] = date('Y年m月d日 H:i', strtotime($vl['pay_time']));
                $dealer_pay_status = $vl['dealer_pay_status'];
                if ($dealer_pay_status == 1 && $vl['business_verify_status'] == 0) {
                    if ($vl['first_pay_money'] > 0) {
                        $collection_status_code = 2;
                    } else {
                        $collection_status_code = 1;
                    }
                } elseif ($dealer_pay_status == 2 && $vl['business_verify_status'] == 1) {
                    if ($vl['first_pay_money'] > 0) {
                        $collection_status_code = 4;
                    } else {
                        $collection_status_code = 3;
                    }
                } elseif ($dealer_pay_status == 4) {       //锁定
                    $collection_status_code = 6;
                } elseif ($dealer_pay_status == 5) {       //收款失败
                    $collection_status_code = 5;
                }
                $list[$key]['collection_status_name'] = C('COLLECTION_TRACK_STATUS')[$collection_status_code];
                //是否显示违约
                $list[$key]['is_again_void'] = true;
                // $changeInfo = changeOrder::detailMap(['order_id' => $vl['order_id'], 'order_status' => $vl['status']]);
                // if ($changeInfo) {
                //     $list[$key]['is_again_void'] = false;
                // }
                if ($vl['is_lock'] == 1) {
                    $list[$key]['is_again_void'] = false;
                }
            }
        }
        $data = ['total' => $total, 'list' => $list];
        return $data;
    }

    /**
     * 获取车商收款跟踪 - 收款明细
     */
    public static function get_dealer_pay_detail($order_id)
    {
        if (empty($order_id)) {
            AuctionException::make_throw('700002');
        }
        $cols = 'o.order_id,o.order_no,o.commision,o.transfer_fee,o.transfer_type,o.company_subsidies,o.is_consult,o.dealer_pay_mode,
               o.bid_best_price,o.bidding_best_price,o.dealer_pay_status,o.coupon,o.dealer_confirm_status,o.compensation,
               c.delivery_mode,ll.first_pay_money,ll.loan_money,ll.xm_list_code';
        $condition['o.order_id'] = ['eq', $order_id];
        $prefix = C('DB_PREFIX');
        $info = M('order')->alias('o')->field($cols)
            ->join($prefix . "cars as c ON c.`car_id`=o.`car_id`")
            ->join(" LEFT JOIN " . $prefix . "loan_log as ll ON ll.`order_id` = o.`order_id`")
            ->where($condition)
            ->find();
        //代金券
        $coupon_money = 0;
        if ($info['coupon'] > 0) {
            $coupon_money = M("coupon_log")->where(['order_id' => $order_id, 'occur_type' => 1])->sum('occur_money');
            $coupon_money = $coupon_money > $info['coupon'] ? $info['coupon'] : $coupon_money;
        }
        $info['coupon_money'] = sprintf("%.2f", $coupon_money);
        //抽奖立减
        $Raffle = new \AuctionCore\Other\Raffle();
        $Raffle_money = $Raffle->find_card_activity($order_id, 1, $state = 1);
        $info['raffle_money'] = $Raffle_money['price'];
        //过户费
        $info['transfer_fee'] = $info['transfer_type'] == 1 ? 0 : $info['transfer_fee'];
        $info['best_price'] = $info['bidding_best_price'] > $info['bid_best_price'] ? $info['bidding_best_price'] : $info['bid_best_price'];
        $info['sum_money'] = sprintf("%.2f", $info['best_price'] + $info['commision'] + $info['transfer_fee']
            - $info['coupon_money'] - $info['raffle_money']);
        if ($info['delivery_mode'] == 2) {
            $info['sum_money'] = sprintf("%.2f", $info['sum_money'] - $info['compensation']);
        }
        if ($info['is_consult'] == 1) {
            $info['final_trade_price'] = sprintf("%.2f", $info['best_price'] + $info['company_subsidies']);
        } else {
            $info['final_trade_price'] = sprintf("%.2f", $info['best_price']);
        }
        return $info;
    }

    /**
     * 获取车商付款价格
     * 应收总额 = 第一名出价 + 交易佣金 + 过户费 - 代金券 - 抽奖立减 - 协商补偿
     * @param $orderId
     * @return string
     * @throws AuctionException
     */
    public static function getDealerPayPrice($orderId)
    {
        if (empty($orderId)) {
            AuctionException::make_throw('700002');
        }
        $price_info = M("order")->field('success_price,commision,transfer_type,transfer_fee,coupon,compensation')->where('order_id=' . $orderId)->find();
        //过户费
        $price_info['transfer_fee'] = $price_info['transfer_type'] == 1 ? 0 : $price_info['transfer_fee'];
        //代金券
        $coupon_money = 0;
        if ($price_info['coupon'] > 0) {
            $coupon_money = M("coupon_log")->where(['order_id' => $orderId, 'occur_type' => 1])->sum('occur_money');
            $coupon_money = $coupon_money > $price_info['coupon'] ? $price_info['coupon'] : $coupon_money;
        }
        $price_info['coupon_money'] = sprintf("%.2f", $coupon_money);
        //抽奖立减
        $Raffle = new \AuctionCore\Other\Raffle();
        $Raffle_money = $Raffle->find_card_activity($orderId, 1, $state = 1);
        $price_info['raffle_money'] = $Raffle_money['price'];
        $price_info['sum_money'] = sprintf("%.2f", $price_info['success_price'] + $price_info['commision'] + $price_info['transfer_fee'] - $coupon_money - $price_info['raffle_money'] - $price_info['compensation']);
        return $price_info['sum_money'];
    }


    /**
     * 更新拍单业务核实状态
     * @param $order_id
     */
    public static function update_order_business_verify_status($order_id)
    {
        if ($order_id < 1) {
            return false;
        }
        return M('order')->where(['order_id' => $order_id])->setField('business_verify_status', 1);
    }
}

//end class
